﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Models.Models;
using System.Text;
using WebApp.Services;

namespace WebApp.Classes
{
    public static class HelperExtensions
    {
        public static MvcHtmlString ImageActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, object routeValues, AjaxOptions ajaxOptions, object htmlAttributes)
        {
            var repID = Guid.NewGuid().ToString();
            var lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes);
            return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText));
        }

        public static MvcHtmlString GetTitle(this HtmlHelper helper, string imagePath, string[] titles)
        {
            var titleString = GetTitleString(imagePath, titles);
            return MvcHtmlString.Create(titleString);
        }

        private static string GetTitleString(string imagePath, string[] titles)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("<ul class=\"breadcrumb\">");
            sb.AppendFormat("<li><img src=\"{0}\" height=\"20px\" /></li> ", HttpContext.Current.Request.ApplicationPath + imagePath);

            foreach (var title in titles)
            {
                if (title == titles[titles.Length - 1])
                {
                    sb.AppendFormat("<li class=\"active\">{0}</li>", title.Substring(title.IndexOf("/") + 1));
                }
                else
                {
                    sb.AppendFormat("<li><a href=\"../{0}\">{1}</a> <span class=\"divider\">/</span></li>", title.Replace(" ", ""), title.Substring(title.IndexOf("/") + 1));
                }
            }

            sb.Append("<ul class=\"pull-right\">");
            sb.Append("<li><img src='" + HttpContext.Current.Request.ApplicationPath + "/Images/glyphicons/png/glyphicons_202_shopping_cart.png' width='15px' />&nbsp;Store:&nbsp;</li>");
            sb.Append(GetStoreDropdown(titles[titles.Length - 1].Replace(" ", "")));
            sb.Append("</ul>");

            sb.Append("</ul>");

            return sb.ToString();
        }

        private static string GetStoreDropdown(string title)
        {
            var user = new UserCookie().Get().User;
            var list = new StoreService().GetStoreListByUser(user, true).StoreList.List;

            if (title == "Account/UserPermissions" || title == "Account/EditUser" || title == "Store/StoreManagement" || title == "Store/EditStore")
            {
                return list.Where(s => s.ID.Equals(user.StoreID)).SingleOrDefault().Name;
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<li class='dropdown'><a style='cursor: pointer;' class='storeSelect dropdown-toggle' data-toggle='dropdown'>{1}<b class='caret'></b></a>", user.StoreID, list.Where(s => s.ID.Equals(user.StoreID)).SingleOrDefault().Name);
            sb.Append("<ul class='dropdown-menu'>");

            foreach (var store in list)
            {
                sb.AppendFormat("<li><a href='" + HttpContext.Current.Request.ApplicationPath + "/Account/ChangeStore?path={2}&storeID={0}'>{1}</a></li>", store.ID, store.Name, title);
            }

            sb.Append("</ul>");
            sb.Append("</li>");

            return sb.ToString();
        }

        public static MvcHtmlString GetMenu(this HtmlHelper helper, IEnumerable<MenuItem> menu, MenuItem item, IEnumerable<MenuItem> subMenu)
        {
            var menuString = GetMenuString(menu, item, subMenu);
            return MvcHtmlString.Create(menuString);
        }

        private static string GetMenuString(IEnumerable<MenuItem> menu, MenuItem item, IEnumerable<MenuItem> subMenu)
        {
            StringBuilder result = new StringBuilder();

            if (subMenu.Count() > 0)
            {
                if (item.UserRights != Enums.GetEnumDescription(Enums.MenuStatus.Invisible))
                {
                    result.AppendFormat("<li class='dropdown'><a class='dropdown-toggle' data-toggle='dropdown' href='{0}'>{1}<b class='caret'></b></a>", item.Path.Length > 0 ? string.Format("{0}/{1}", HttpContext.Current.Request.ApplicationPath, item.Path) : string.Empty, GetMenuIcon(item.Name));
                    result.Append("<ul class='dropdown-menu'>");
                }

                foreach (var subItem in subMenu.OrderBy(o => o.Order))
                {
                    bool isDrop = false;

                    if (menu.Where(o => o.ParentID.Equals(subItem.AppID)).Count() > 0)
                    {
                        isDrop = true;
                    }

                    if (isDrop)
                    {
                        if (subItem.UserRights != Enums.GetEnumDescription(Enums.MenuStatus.Invisible))
                        {
                            result.Append(GetMenuString(menu, subItem, menu.Where(o => o.ParentID.Equals(subItem.AppID))));
                        }
                    }
                    else
                    {
                        if (subItem.UserRights != Enums.GetEnumDescription(Enums.MenuStatus.Invisible))
                        {
                            result.AppendFormat("<li><a href='{0}'>{1}</a></li>", string.Format("{0}/{1}", HttpContext.Current.Request.ApplicationPath, subItem.Path), GetMenuIcon(subItem.Name));
                        }
                    }
                }

                if (item.UserRights != Enums.GetEnumDescription(Enums.MenuStatus.Invisible))
                {
                    result.Append("</ul>");
                    result.Append("</li>");
                }
            }
            else
            {
                if (item.UserRights != Enums.GetEnumDescription(Enums.MenuStatus.Invisible))
                {
                    result.AppendFormat("<li><a href='{0}'>{1}</a></li>", string.Format("{0}/{1}", HttpContext.Current.Request.ApplicationPath, item.Path), GetMenuIcon(item.Name));
                }
            }

            return result.ToString();
        }

        private static string GetMenuIcon(string name)
        {
            return name.Replace("$|", "<").Replace("|$", ">").Replace("~", System.Web.HttpContext.Current.Request.ApplicationPath) + "";
        }

        public static MvcHtmlString GetLookUp(this HtmlHelper helper, string id, string status, string entity, string cssClass = "input-medium", string attributes = "")
        {
            var lookupString = GetLookUpString(id, status, entity, cssClass, attributes);
            return MvcHtmlString.Create(lookupString);
        }

        private static string GetLookUpString(string id, string status, string entity, string cssClass, string attributes)
        {
            var lookups = new Services.ServiceService().GetLookUp(entity);

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("<select id='status{0}' name='status{0}' class='{1}' {2}>", id, cssClass, attributes);
            foreach (var lookup in lookups.LookUpList)
            {
                sb.AppendFormat("<option value='{0}' {1}>{2}</option>", lookup.Key, (lookup.Value == status ? "selected='selected'" : string.Empty), lookup.Value);
            }
            sb.Append("</select>");

            return sb.ToString();
        }
    }
}